package com.ice.framework.rocketmq.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.ice.framework.rocketmq.dto.UserDto;
import com.yomahub.tlog.core.rpc.TLogLabelBean;
import com.yomahub.tlog.core.rpc.TLogRPCHandler;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author wangwei
 * @Date 2023/8/15 15:25
 */
@Component
@RocketMQMessageListener(consumerGroup = "${rocketmq.consumer.user.group}", topic = "${rocketmq.consumer.topic}",
        selectorExpression = "${rocketmq.consumer.user.tag}", messageModel = MessageModel.CLUSTERING)
public class UserConsumer implements RocketMQListener<MessageExt> {
    private final TLogRPCHandler tLogRPCHandler = new TLogRPCHandler();
    public static Logger logger = LoggerFactory.getLogger(UserConsumer.class);

    @Override
    public void onMessage(MessageExt message) {
        Map<String, String> properties = message.getProperties();
        String tlogTraceId = properties.get("tlogTraceId");
        String tlogSpanId = properties.get("tlogSpanId");
        TLogLabelBean tLogLabelBean = new TLogLabelBean();
        tLogLabelBean.setTraceId(tlogTraceId);
        tLogLabelBean.setSpanId(tlogSpanId);
        tLogRPCHandler.processProviderSide(tLogLabelBean);
        logger.info("传递过来的消息头：{}", JSON.toJSONString(properties));
        try {
            String bodyStr = new String(message.getBody(), StandardCharsets.UTF_8);
            UserDto userDto = JSON.parseObject(bodyStr, UserDto.class);
            logger.info("传递过来的消息：{}", JSON.toJSONString(userDto));
        } finally {
            tLogRPCHandler.cleanThreadLocal();
        }
    }
}
